<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Java线程 | C·辰</title><meta name="author" content="辰"><meta name="copyright" content="辰"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Java线程">
<meta property="og:type" content="article">
<meta property="og:title" content="Java线程">
<meta property="og:url" content="http://example.com/2023/05/01/Java%E7%BA%BF%E7%A8%8B/index.html">
<meta property="og:site_name" content="C·辰">
<meta property="og:description" content="Java线程">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/thread.webp">
<meta property="article:published_time" content="2023-05-01T14:22:22.000Z">
<meta property="article:modified_time" content="2023-07-27T10:11:57.810Z">
<meta property="article:author" content="辰">
<meta property="article:tag" content="Java线程">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/thread.webp"><link rel="shortcut icon" href="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Bell.ico"><link rel="canonical" href="http://example.com/2023/05/01/Java%E7%BA%BF%E7%A8%8B/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java线程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-27 18:11:57'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Favatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">32</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Demo</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/c2c_shop/"><i class="fa-fw fa fa-comments-o"></i><span> 商城</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/thread2.webp')"><nav id="nav"><span id="blog-info"><a href="/" title="C·辰"><span class="site-name">C·辰</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-graduation-cap"></i><span> 博文</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw fa fa-folder-open"></i><span> 归档</span></a></li></ul></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> Demo</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/c2c_shop/"><i class="fa-fw fa fa-comments-o"></i><span> 商城</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java线程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-05-01T14:22:22.000Z" title="发表于 2023-05-01 22:22:22">2023-05-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-27T10:11:57.810Z" title="更新于 2023-07-27 18:11:57">2023-07-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>20分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java线程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230627161401445.png" alt="image-20230627161401445"></p>
<h1 id="线程实现【重点】"><a href="#线程实现【重点】" class="headerlink" title="线程实现【重点】"></a>线程实现【重点】</h1><blockquote>
<ul>
<li><p>线程名字</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//主线程定义线程名字并启动</span></span><br><span class="line"><span class="keyword">new</span> <span class="title class_">Thread</span>(testThread5,<span class="string">&quot;销售A&quot;</span>).start();</span><br><span class="line"></span><br><span class="line"><span class="comment">//线程内获取当前线程名字</span></span><br><span class="line">Thread.currentThread().getName()</span><br></pre></td></tr></table></figure></li>
</ul>
</blockquote>
<h2 id="Thread"><a href="#Thread" class="headerlink" title="Thread"></a>Thread</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230627161641749.png" alt="image-20230627161641749"></p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230627162037653.png" alt="image-20230627162037653"></p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230627164616243.png" alt="image-20230627164616243"></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//创建线程的方式一：继承Thread类，重写run()方法，调用start开启线程</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestThread1</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//run方法线程体</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">200</span>; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;我在看代码---&quot;</span> + i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//main线程，主线程</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//创建一个线程对象</span></span><br><span class="line">        TestThread1 testThread1=<span class="keyword">new</span> <span class="title class_">TestThread1</span>();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//调用 start() 方法开启线程:同时运行，交替执行</span></span><br><span class="line">        testThread1.start();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//调用 run() 方法先跑线程</span></span><br><span class="line">        <span class="comment">//testThread1.run();</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">200</span>; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;我在学习多线程--&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">     </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<h3 id="注意"><a href="#注意" class="headerlink" title="注意"></a>注意</h3><ul>
<li>继承<strong>Thread</strong>类，重写run()方法，调用<strong>start</strong>开启线程</li>
<li>线程开启不一定立即执行，由cpu调度执行</li>
<li>java单继承，继承Thread无法继承其他类</li>
</ul>
</blockquote>
<ul>
<li>练习 –  使用多线程同时下载多张图片案例</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//实现多线程同步下载图片</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestThread2</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String url;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">TestThread2</span><span class="params">(String url,String name)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.url=url;</span><br><span class="line">        <span class="built_in">this</span>.name=name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//下载图片线程的执行体</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        WebDownloader webDownloader=<span class="keyword">new</span> <span class="title class_">WebDownloader</span>();</span><br><span class="line">        webDownloader.downloader(url,name);</span><br><span class="line">        System.out.println(<span class="string">&quot;下载了文件名为：&quot;</span>+name);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">TestThread2</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestThread2</span>(<span class="string">&quot;https://chen-131.png&quot;</span>,<span class="string">&quot;1.png&quot;</span>);</span><br><span class="line">        <span class="type">TestThread2</span> <span class="variable">t2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestThread2</span>(<span class="string">&quot;https://chen-131.jpg&quot;</span>,<span class="string">&quot;2.jpg&quot;</span>);</span><br><span class="line">        <span class="type">TestThread2</span> <span class="variable">t3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestThread2</span>(<span class="string">&quot;https://chen-131.png&quot;</span>,<span class="string">&quot;3.png&quot;</span>);</span><br><span class="line"></span><br><span class="line">        t1.start();</span><br><span class="line">        t2.start();</span><br><span class="line">        t3.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//下载器</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">WebDownloader</span>&#123;</span><br><span class="line">    <span class="comment">//下载方法</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">downloader</span><span class="params">(String url,String name)</span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            FileUtils.copyURLToFile(<span class="keyword">new</span> <span class="title class_">URL</span>(url),<span class="keyword">new</span> <span class="title class_">File</span>(name));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            System.out.println(<span class="string">&quot;IO异常，downloader方法出现问题&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>下载  –  导包  –  commons-io</p>
</blockquote>
<br>

<br>

<hr>
<br>

<br>



<h2 id="Runnable【-】"><a href="#Runnable【-】" class="headerlink" title="Runnable【*】"></a><strong>Runnable【*】</strong></h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230627161656312.png" alt="image-20230627161656312"></p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230628005138151.png" alt="image-20230628005138151"></p>
<blockquote>
<ul>
<li>实现 Runnable 接口</li>
<li>实现 run() 方法</li>
<li>创建 Thread 对象 来开启 start()  线程</li>
</ul>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//创建线程方法2：实现runable接口，重写run方法，执行线程需要丢入runnable接口实现类，调用start方法</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestThread3</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span> &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//run方法线程体</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">200</span>; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;我在看代码---&quot;</span> + i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建runnable接口的实现类对象</span></span><br><span class="line">        <span class="type">TestThread3</span> <span class="variable">testThread3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestThread3</span>();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建线程对象，通过线程对象来开启我们的线程，代理</span></span><br><span class="line">        <span class="comment">//Thread thread = new Thread(testThread3);</span></span><br><span class="line">        <span class="comment">//thread.start();</span></span><br><span class="line">         </span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(testThread3).start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">1000</span>; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;我在学习多线程--&quot;</span> + i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ul>
<li>练习 –  使用多线程同时下载多张图片</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//和继承Thread类使用方法基本一致。只不过是启动线程需要改变</span></span><br><span class="line"></span><br><span class="line">     <span class="keyword">new</span> <span class="title class_">Thread</span>(t1).start();</span><br><span class="line">     <span class="keyword">new</span> <span class="title class_">Thread</span>(t2).start();</span><br><span class="line">     <span class="keyword">new</span> <span class="title class_">Thread</span>(t3).start();</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br>

<br>

<ul>
<li>龟兔赛跑案例</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//模拟龟兔赛跑</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Race</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//胜利者</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> String winner;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">1</span>; i &lt;= <span class="number">100</span>; i++) &#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//模拟兔子休息</span></span><br><span class="line">            <span class="keyword">if</span> (Thread.currentThread().getName().equals(<span class="string">&quot;兔子&quot;</span>)&amp;&amp;i%<span class="number">10</span>==<span class="number">0</span>)&#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">2</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//判断比赛是否结束</span></span><br><span class="line">            <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> gameOver(i);</span><br><span class="line">            <span class="comment">//比赛结束，停止程序</span></span><br><span class="line">            <span class="keyword">if</span> (flag)&#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;--&gt;跑了&quot;</span>+i+<span class="string">&quot;步&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//判断是否完成比赛</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">boolean</span> <span class="title function_">gameOver</span><span class="params">(<span class="type">int</span> steps)</span>&#123;</span><br><span class="line">        <span class="comment">//判断是否有胜利者</span></span><br><span class="line">        <span class="keyword">if</span> (winner!=<span class="literal">null</span>)&#123;<span class="comment">//已经存在胜利者了</span></span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (steps&gt;=<span class="number">100</span>)&#123;</span><br><span class="line">                winner=Thread.currentThread().getName();</span><br><span class="line">                System.out.println(<span class="string">&quot;winner is &quot;</span>+winner);</span><br><span class="line">                <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Race</span> <span class="variable">race</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Race</span>();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(race,<span class="string">&quot;兔子&quot;</span>).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(race,<span class="string">&quot;乌龟&quot;</span>).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>





<hr>
<br>

<br>

<h2 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230628013956991.png" alt="image-20230628013956991"></p>
<br>

<br>

<hr>
<br>

<br>

<h2 id="Callable"><a href="#Callable" class="headerlink" title="Callable"></a>Callable</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230627161721072.png" alt="image-20230627161721072"></p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230628182953554.png" alt="image-20230628182953554"></p>
<blockquote>
<ul>
<li><p>线程创建方式三：实现callable接口</p>
</li>
<li><p>callable的好处</p>
<ul>
<li>1.可以定义返回值</li>
<li>2.可以抛出异常</li>
</ul>
</li>
</ul>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestCallabel</span> <span class="keyword">implements</span> <span class="title class_">Callable</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String url;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">TestCallabel</span><span class="params">(String url,String name)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.url=url;</span><br><span class="line">        <span class="built_in">this</span>.name=name;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//下载图片线程的执行体</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> Boolean <span class="title function_">call</span><span class="params">()</span> &#123;</span><br><span class="line">        WebDownloader webDownloader=<span class="keyword">new</span> <span class="title class_">WebDownloader</span>();</span><br><span class="line">        webDownloader.downloader(url,name);</span><br><span class="line">        System.out.println(<span class="string">&quot;下载了文件名为：&quot;</span>+name);</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> ExecutionException, InterruptedException &#123;</span><br><span class="line">        <span class="type">TestCallabel</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestCallabel</span>(<span class="string">&quot;https://chen-1.png&quot;</span>,<span class="string">&quot;1.png&quot;</span>);</span><br><span class="line">        <span class="type">TestCallabel</span> <span class="variable">t2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestCallabel</span>(<span class="string">&quot;https://chen-1.jpg&quot;</span>,<span class="string">&quot;2.jpg&quot;</span>);</span><br><span class="line">        <span class="type">TestCallabel</span> <span class="variable">t3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestCallabel</span>(<span class="string">&quot;https://chen-1.png&quot;</span>,<span class="string">&quot;3.png&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建执行服务</span></span><br><span class="line">        <span class="type">ExecutorService</span> <span class="variable">service</span> <span class="operator">=</span> Executors.newFixedThreadPool(<span class="number">3</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//提交执行</span></span><br><span class="line">        Future&lt;Boolean&gt; r1 = service.submit(t1);</span><br><span class="line">        Future&lt;Boolean&gt; r2 = service.submit(t2);</span><br><span class="line">        Future&lt;Boolean&gt; r3 = service.submit(t3);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取结果</span></span><br><span class="line">        <span class="type">boolean</span> <span class="variable">rs1</span> <span class="operator">=</span> r1.get();</span><br><span class="line">        <span class="type">boolean</span> <span class="variable">rs2</span> <span class="operator">=</span> r2.get();</span><br><span class="line">        <span class="type">boolean</span> <span class="variable">rs3</span> <span class="operator">=</span> r3.get();</span><br><span class="line"></span><br><span class="line">        System.out.println(rs1);</span><br><span class="line">        System.out.println(rs2);</span><br><span class="line">        System.out.println(rs3);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭服务</span></span><br><span class="line">        service.shutdownNow();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//下载器</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">WebDownloader</span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">downloader</span><span class="params">(String url,String name)</span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            FileUtils.copyURLToFile(<span class="keyword">new</span> <span class="title class_">URL</span>(url),<span class="keyword">new</span> <span class="title class_">File</span>(name));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            System.out.println(<span class="string">&quot;IO异常，downloader方法出现问题&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<br>

<br>

<h2 id="Lambda表达式"><a href="#Lambda表达式" class="headerlink" title="Lambda表达式"></a>Lambda表达式</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230628214936098.png" alt="image-20230628214936098"></p>
<blockquote>
<ul>
<li>函数式接口<ul>
<li>只有一个抽象方法</li>
</ul>
</li>
</ul>
</blockquote>
<ul>
<li>原写法</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestLambdal</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">ILike</span> <span class="variable">iLike</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Like</span>();</span><br><span class="line">        iLike.lambda();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//1.定义一个函数式接口</span></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">ILike</span>&#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">lambda</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//2.实现类</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Like</span> <span class="keyword">implements</span>  <span class="title class_">ILike</span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">lambda</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;I Like Lambda&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<ul>
<li><strong>推导lambda写法</strong></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestLambdal</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//用Lambda简化</span></span><br><span class="line">        <span class="type">ILike</span> <span class="variable">iLike</span> <span class="operator">=</span> () -&gt;&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;I Like Lambda5&quot;</span>);</span><br><span class="line">        &#125;;</span><br><span class="line">        iLike.lambda();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">定义一个函数式接口</span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">ILike</span>&#123;</span><br><span class="line">    <span class="keyword">void</span> <span class="title function_">lambda</span><span class="params">()</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ul>
<li>简化写法</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestLambda2</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//lambda</span></span><br><span class="line">        CP cpe=<span class="literal">null</span>;</span><br><span class="line"></span><br><span class="line">         <span class="comment">//原型</span></span><br><span class="line">        cpe=(<span class="type">int</span> a)-&gt;&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;lambda ： cpe--&gt;&quot;</span> + a);</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//简化1.去除参数类型 ------------  推荐  -----------------------------</span></span><br><span class="line">        cpe = (a)-&gt;&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;lambda ： cpe--&gt;&quot;</span> + a);</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//简化2.简化括号 </span></span><br><span class="line">        cpe = a -&gt; &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;lambda ： cpe--&gt;&quot;</span> + a);</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//简化3.去掉花括号</span></span><br><span class="line">        cpe = a-&gt; System.out.println(<span class="string">&quot;lambda ： cpe--&gt;&quot;</span> + a);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">CP</span>&#123;</span><br><span class="line">    <span class="keyword">void</span>  <span class="title function_">cpe</span><span class="params">(<span class="type">int</span> a)</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<p>总结：</p>
<ul>
<li><p>lambada表达式只能有一行代码的情况下才能简化成一行，如果有多行，那么就用代码块包裹</p>
</li>
<li><p>前提是接口为函数式接口</p>
</li>
<li><p>多个参数也可以去掉参数类型，要去掉就都去掉，必须加上括号(a,b)，</p>
</li>
</ul>
</blockquote>
<hr>
<br>

<br>

<h1 id="线程状态"><a href="#线程状态" class="headerlink" title="线程状态"></a>线程状态</h1><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629002043736.png" alt="image-20230629002043736"></p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629002216764.png" alt="image-20230629002216764"></p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629002309248.png" alt="image-20230629002309248"></p>
<br>

<h2 id="观察线程状态"><a href="#观察线程状态" class="headerlink" title="观察线程状态"></a>观察线程状态</h2><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestState</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">thread</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">            <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;//////&quot;</span>);</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//获取线程状态</span></span><br><span class="line">        Thread.<span class="type">State</span> <span class="variable">state</span> <span class="operator">=</span> thread.getState();</span><br><span class="line">        System.out.println(state);  <span class="comment">//输出为：NEW</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//观察启动</span></span><br><span class="line">        thread.start();<span class="comment">//启动线程</span></span><br><span class="line">        state = thread.getState();</span><br><span class="line">        System.out.println(state);<span class="comment">//输出为：RUN</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (state != Thread.State.TERMINATED) &#123;</span><br><span class="line">            <span class="comment">//只要线程不终止，就一直输出状态</span></span><br><span class="line">            Thread.sleep(<span class="number">100</span>);</span><br><span class="line">            state = thread.getState();<span class="comment">//更新线程状态</span></span><br><span class="line">            System.out.println(state);<span class="comment">//输出状态</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<br>

<h2 id="线程停止-–stop"><a href="#线程停止-–stop" class="headerlink" title="线程停止 –stop"></a>线程停止 –stop</h2><blockquote>
<p>1.建议线程正常停止 —–&gt;  利用次数，不建议死循环</p>
<p>2.建议使用标志位  –&gt;  设置一个标志位</p>
<p>3.不要使用  stop  或者  destroy  等过时或者JDK不建议使用的方法</p>
</blockquote>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629003650091.png" alt="image-20230629003650091"></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestTop</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//1.设置一个标识位</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">boolean</span> flag= <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">int</span> i=<span class="number">0</span>;</span><br><span class="line">        <span class="keyword">while</span>(flag)&#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;run.....Thread  &quot;</span>+i++);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//2.设置一个公开的方法停止线程，转换标志位</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span>  <span class="title function_">stop</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.flag=<span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">         </span><br><span class="line">        <span class="type">TestTop</span> <span class="variable">testTop</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestTop</span>();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(testTop).start();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">1000</span>; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;main  &quot;</span>+i);</span><br><span class="line">            <span class="keyword">if</span> (i==<span class="number">900</span>)&#123;</span><br><span class="line">                <span class="comment">//调用stop方法切换标志位，让线程停止</span></span><br><span class="line">                testTop.stop();</span><br><span class="line">                System.out.println(<span class="string">&quot;该线程停止了&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br>

<h2 id="线程休眠–sleep"><a href="#线程休眠–sleep" class="headerlink" title="线程休眠–sleep"></a>线程休眠–sleep</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629003935215.png" alt="image-20230629003935215"></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//主线程打印当前系统时间</span></span><br><span class="line"><span class="type">Date</span> <span class="variable">startTime</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Date</span>(System.currentTimeMillis());<span class="comment">//获取系统当前时间</span></span><br><span class="line"><span class="keyword">while</span> (<span class="literal">true</span>)&#123;</span><br><span class="line">     <span class="keyword">try</span> &#123;</span><br><span class="line">          Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">          System.out.println(<span class="keyword">new</span> <span class="title class_">SimpleDateFormat</span>(<span class="string">&quot;HH:mm:ss&quot;</span>).format(startTime));</span><br><span class="line">          startTime = <span class="keyword">new</span> <span class="title class_">Date</span>(System.currentTimeMillis());<span class="comment">//更新当前时间</span></span><br><span class="line">     &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">          e.printStackTrace();</span><br><span class="line">     &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h2 id="线程礼让–yield"><a href="#线程礼让–yield" class="headerlink" title="线程礼让–yield"></a>线程礼让–yield</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629005539522.png" alt="image-20230629005539522"></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestYield</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">MyYield</span> <span class="variable">myYield</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MyYield</span>();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(myYield,<span class="string">&quot;a&quot;</span>).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(myYield,<span class="string">&quot;b&quot;</span>).start();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyYield</span> <span class="keyword">implements</span>  <span class="title class_">Runnable</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;线程开始执行&quot;</span>);</span><br><span class="line">        Thread.<span class="keyword">yield</span>();<span class="comment">//礼让</span></span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;线程停止执行&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h2 id="合并线程–join"><a href="#合并线程–join" class="headerlink" title="合并线程–join"></a>合并线程–join</h2><ul>
<li>Join合并线程，待此线程执行完成后，再执行其他线程，其他线程阻塞</li>
<li>插队</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestJoin</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">10000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;线程vip来了&quot;</span>+i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="comment">//启动我们的线程</span></span><br><span class="line">        <span class="type">TestJoin</span> <span class="variable">testJoin</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestJoin</span>();</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">thread</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(testJoin);</span><br><span class="line">        thread.start();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//主线程</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">1000</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (i==<span class="number">200</span>)&#123;</span><br><span class="line">                thread.join();<span class="comment">//插队</span></span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;man  &quot;</span>+i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br>

<h2 id="线程优先级–priority"><a href="#线程优先级–priority" class="headerlink" title="线程优先级–priority"></a>线程优先级–priority</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629014945533.png" alt="image-20230629014945533"></p>
<ul>
<li>先设置优先级，再启动</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestPriority</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//主线程优先级--5</span></span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;--&gt;&quot;</span>+Thread.currentThread().getPriority());</span><br><span class="line"></span><br><span class="line">        <span class="type">MyPrority</span> <span class="variable">myPrority</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MyPrority</span>();</span><br><span class="line"></span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(myPrority);</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(myPrority);</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t3</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(myPrority);</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t4</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(myPrority);</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t5</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(myPrority);</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">t6</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Thread</span>(myPrority);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//先设置优先级，再启动</span></span><br><span class="line">        t1.start();</span><br><span class="line"></span><br><span class="line">        t2.setPriority(<span class="number">2</span>);</span><br><span class="line">        t2.start();</span><br><span class="line"></span><br><span class="line">        t3.setPriority(<span class="number">6</span>);</span><br><span class="line">        t3.start();</span><br><span class="line"></span><br><span class="line">        t4.setPriority(Thread.MAX_PRIORITY);</span><br><span class="line">        t4.start();</span><br><span class="line"></span><br><span class="line">        t5.setPriority(Thread.MIN_PRIORITY);</span><br><span class="line">        t5.start();</span><br><span class="line"></span><br><span class="line">        t6.setPriority(<span class="number">1</span>);</span><br><span class="line">        t6.start();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyPrority</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;--&gt;&quot;</span>+Thread.currentThread().getPriority());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<br>

<h2 id="守护线程–daemon"><a href="#守护线程–daemon" class="headerlink" title="守护线程–daemon"></a>守护线程–daemon</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629133341524.png" alt="image-20230629133341524"></p>
<ul>
<li><p>即 守护线程 会**陪伴 **被守护的线程 执行完毕</p>
</li>
<li><pre><code class="java">//true则设置为守护线程
//默认是false表示是用户线程，正常的线程都是用户线程
 thread.setDaemon(true);
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line">  </span><br><span class="line"></span><br><span class="line">```java</span><br><span class="line">public class TestDaemon &#123;</span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        God god = new God();</span><br><span class="line">        You you = new You();</span><br><span class="line"></span><br><span class="line">        Thread thread = new Thread(god);</span><br><span class="line">        thread.setDaemon(true);//默认是false表示是用户线程，正常的线程都是用户线程</span><br><span class="line"></span><br><span class="line">        thread.start();//保护线程启动</span><br><span class="line"></span><br><span class="line">        new Thread(you).start();//用户线程启动</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//守护线程</span><br><span class="line">class God implements Runnable&#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        while (true)&#123;</span><br><span class="line">            System.out.println(&quot;保护着你&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//被守护的线程</span><br><span class="line">class You implements Runnable&#123;</span><br><span class="line"></span><br><span class="line">    @Override</span><br><span class="line">    public void run() &#123;</span><br><span class="line">        for (int i = 0; i &lt; 36500; i++) &#123;</span><br><span class="line">            System.out.println(&quot;开心&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(&quot;==================bye====================&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</code></pre>
</li>
</ul>
<br>

<br>

<hr>
<br>

<br>

<h1 id="线程同步【重点】"><a href="#线程同步【重点】" class="headerlink" title="线程同步【重点】"></a>线程同步【重点】</h1><h2 id="并发"><a href="#并发" class="headerlink" title="并发"></a>并发</h2><ul>
<li>多个线程操作同一个资源</li>
<li>等待机制  – <strong>对象等待池</strong></li>
</ul>
<h3 id="安全集合CopyOnWriteArrayList"><a href="#安全集合CopyOnWriteArrayList" class="headerlink" title="安全集合CopyOnWriteArrayList"></a>安全集合CopyOnWriteArrayList</h3><blockquote>
<p>不需要锁，各线程排队进行</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//测试JUC安全类型的集合</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestJUC</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        CopyOnWriteArrayList&lt;String&gt; list = <span class="keyword">new</span> <span class="title class_">CopyOnWriteArrayList</span>();</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">1000</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">                list.add(Thread.currentThread().getName());</span><br><span class="line">            &#125;).start();</span><br><span class="line">        &#125;</span><br><span class="line">        Thread.sleep(<span class="number">100</span>);</span><br><span class="line">        System.out.println(list.size());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h2 id="锁机制-–-synchronized"><a href="#锁机制-–-synchronized" class="headerlink" title="锁机制  –  synchronized"></a>锁机制  –  synchronized</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629165131152.png" alt="image-20230629165131152"></p>
<h3 id="synchronized方法"><a href="#synchronized方法" class="headerlink" title="synchronized方法"></a>synchronized方法</h3><blockquote>
<p>锁 类本身  private synchronized void buy(){  }</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UnsafeBuyTicket</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">BuyTicket</span> <span class="variable">station</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">BuyTicket</span>();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(station,<span class="string">&quot;A员工&quot;</span>).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(station,<span class="string">&quot;B员工&quot;</span>).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(station,<span class="string">&quot;C员工&quot;</span>).start();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">BuyTicket</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="type">int</span> <span class="variable">ticketNums</span> <span class="operator">=</span> <span class="number">10</span>;</span><br><span class="line">    <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//买票</span></span><br><span class="line">        <span class="keyword">while</span> (flag)&#123;</span><br><span class="line">            buy();</span><br><span class="line">            <span class="comment">//模拟延时</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep(<span class="number">100</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//synchronized  同步方法，锁的是this</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title function_">buy</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">//判断是否有票</span></span><br><span class="line">        <span class="keyword">if</span> (ticketNums&lt;=<span class="number">0</span>)&#123;</span><br><span class="line">            flag=<span class="literal">false</span>;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//买票</span></span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;拿到&quot;</span>+ticketNums--);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h3 id="synchronized块"><a href="#synchronized块" class="headerlink" title="synchronized块"></a>synchronized块</h3><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629181507934.png" alt="image-20230629181507934"></p>
<blockquote>
<ul>
<li>可以锁任意对象   synchronized (account){  }</li>
<li><strong>锁的对象：变化的量，需要增删改的量</strong></li>
</ul>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.synchronizedc;</span><br><span class="line"></span><br><span class="line"><span class="comment">//不安全的取钱</span></span><br><span class="line"><span class="comment">//两人取，账户</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">UnsafeBank</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//账户</span></span><br><span class="line">        <span class="type">Account</span> <span class="variable">account</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Account</span>(<span class="number">1000</span>,<span class="string">&quot;结婚基金&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="type">Drawing</span> <span class="variable">you</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Drawing</span>(account,<span class="number">50</span>,<span class="string">&quot;你&quot;</span>);</span><br><span class="line">        <span class="type">Drawing</span> <span class="variable">girlFirend</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Drawing</span>(account,<span class="number">100</span>,<span class="string">&quot;girlFirend&quot;</span>);</span><br><span class="line">        girlFirend.start();</span><br><span class="line">        you.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//账号</span></span><br><span class="line"><span class="keyword">class</span>  <span class="title class_">Account</span>&#123;</span><br><span class="line">    <span class="type">int</span> money;</span><br><span class="line">    String name;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Account</span><span class="params">(<span class="type">int</span> money, String name)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.money = money;</span><br><span class="line">        <span class="built_in">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//银行：模拟取款</span></span><br><span class="line"><span class="keyword">class</span>  <span class="title class_">Drawing</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line">    Account account;<span class="comment">//账号</span></span><br><span class="line">    <span class="comment">//取多少钱</span></span><br><span class="line">    <span class="type">int</span> drawingMoney;</span><br><span class="line">    <span class="comment">//手里</span></span><br><span class="line">    <span class="type">int</span> nowMoney;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Drawing</span><span class="params">(Account account,<span class="type">int</span> drawingMoney,String name)</span>&#123;</span><br><span class="line">        <span class="built_in">super</span>(name);</span><br><span class="line">        <span class="built_in">this</span>.account=account;</span><br><span class="line">        <span class="built_in">this</span>.drawingMoney=drawingMoney;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//取钱</span></span><br><span class="line">    <span class="comment">//synchronized 默认锁this</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span>  <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (account)&#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//判断有没有钱</span></span><br><span class="line">            <span class="keyword">if</span> (account.money-drawingMoney&lt;<span class="number">0</span>)&#123;</span><br><span class="line">                System.out.println(Thread.currentThread().getName()+<span class="string">&quot;不够，取不了&quot;</span>);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//余额</span></span><br><span class="line">            account.money=account.money-drawingMoney;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//手里的钱</span></span><br><span class="line">            nowMoney=nowMoney+drawingMoney;</span><br><span class="line"></span><br><span class="line">            System.out.println(account.name+<span class="string">&quot;余额为:&quot;</span>+account.money);</span><br><span class="line">            <span class="comment">//Thread.currentThread().getName()==this.getName()</span></span><br><span class="line">            System.out.println(<span class="built_in">this</span>.getName()+<span class="string">&quot;手里的钱：&quot;</span>+nowMoney);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<br>

<h2 id="死锁"><a href="#死锁" class="headerlink" title="死锁"></a>死锁</h2><ul>
<li>多个线程互相抱着对方需要的资源，然后形成僵持</li>
</ul>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629213148270.png" alt="image-20230629213148270"></p>
<ul>
<li>使用 synchronized块 上锁和解锁</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//死锁：多个线程互相抱着对方需要的资源，然后形成僵持</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">DeadLock</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">Makeup</span> <span class="variable">g1</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Makeup</span>(<span class="number">0</span>,<span class="string">&quot;灰姑凉&quot;</span>);</span><br><span class="line">        <span class="type">Makeup</span> <span class="variable">g2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Makeup</span>(<span class="number">1</span>,<span class="string">&quot;白雪公主&quot;</span>);</span><br><span class="line">        g1.start();</span><br><span class="line">        g2.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//口红</span></span><br><span class="line"><span class="keyword">class</span>  <span class="title class_">Lipstick</span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//镜子</span></span><br><span class="line"><span class="keyword">class</span>  <span class="title class_">Mirror</span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Makeup</span> <span class="keyword">extends</span> <span class="title class_">Thread</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//需要的资源只有一份，用static来保证只有一份</span></span><br><span class="line">    <span class="keyword">static</span> <span class="type">Lipstick</span> <span class="variable">lipstick</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Lipstick</span>();</span><br><span class="line">    <span class="keyword">static</span> <span class="type">Mirror</span> <span class="variable">mirror</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Mirror</span>();</span><br><span class="line">    <span class="type">int</span> choice;<span class="comment">//选择</span></span><br><span class="line">    String girlName;<span class="comment">//使用化妆品的人</span></span><br><span class="line"></span><br><span class="line">    Makeup(<span class="type">int</span> choice, String girlName) &#123;</span><br><span class="line">        <span class="built_in">this</span>.choice = choice;</span><br><span class="line">        <span class="built_in">this</span>.girlName = girlName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//化妆</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            makeup();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//化妆，互相持有对方的锁，就是需要拿到对方的资源</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">void</span> <span class="title function_">makeup</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException &#123;</span><br><span class="line">        <span class="keyword">if</span> (choice == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (lipstick) &#123;<span class="comment">//获得口红的锁</span></span><br><span class="line">                System.out.println(<span class="built_in">this</span>.girlName + <span class="string">&quot;获得口红的锁&quot;</span>);</span><br><span class="line">                Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">synchronized</span> (mirror) &#123;<span class="comment">//一秒后获取镜子的锁</span></span><br><span class="line">                System.out.println(<span class="built_in">this</span>.girlName + <span class="string">&quot;获得镜子的锁&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (mirror) &#123;<span class="comment">//获得镜子的锁</span></span><br><span class="line">                System.out.println(<span class="built_in">this</span>.girlName + <span class="string">&quot;获得镜子的锁&quot;</span>);</span><br><span class="line">                Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">synchronized</span> (lipstick) &#123;<span class="comment">//2秒后获取口红的锁</span></span><br><span class="line">                System.out.println(<span class="built_in">this</span>.girlName + <span class="string">&quot;获得口红的锁&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629215343031.png" alt="image-20230629215343031"></p>
<br>

<h2 id="Lock（锁）"><a href="#Lock（锁）" class="headerlink" title="Lock（锁）"></a>Lock（锁）</h2><ul>
<li><h2 id="ReentrantLock"><a href="#ReentrantLock" class="headerlink" title="ReentrantLock"></a>ReentrantLock</h2></li>
</ul>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629215546621.png" alt="image-20230629215546621"></p>
<blockquote>
<ul>
<li>定义：private final ReentrantLock lock &#x3D; new ReentrantLock();</li>
<li><strong>在 try 中上锁，finally 中解锁</strong></li>
<li>显式锁，手动开启和关闭</li>
<li><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629220630609.png" alt="image-20230629220630609"></li>
</ul>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestLock</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">TestLock2</span> <span class="variable">testLock2</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TestLock2</span>();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(testLock2).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(testLock2).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(testLock2).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">TestLock2</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line">    <span class="type">int</span> <span class="variable">ticketNums</span> <span class="operator">=</span> <span class="number">10</span>;</span><br><span class="line">  </span><br><span class="line">    <span class="comment">//定义lock锁</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="type">ReentrantLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">while</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                lock.lock();<span class="comment">//加锁</span></span><br><span class="line">                <span class="keyword">if</span> (ticketNums&gt;<span class="number">0</span>)&#123;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                    System.out.println(ticketNums--);</span><br><span class="line">                &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">                lock.unlock();<span class="comment">//解锁</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<p>总结：</p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629220820159.png" alt="image-20230629220820159"></p>
</blockquote>
<br>

<br>

<hr>
<br>

<br>

<h1 id="线程通信问题"><a href="#线程通信问题" class="headerlink" title="线程通信问题"></a>线程通信问题</h1><h2 id="生产者消费者模式"><a href="#生产者消费者模式" class="headerlink" title="生产者消费者模式"></a>生产者消费者模式</h2><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629235829001.png" alt="image-20230629235829001"></p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230629235942756.png" alt="image-20230629235942756"></p>
<h3 id="管程法"><a href="#管程法" class="headerlink" title="管程法"></a>管程法</h3><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230630000140407.png" alt="image-20230630000140407"></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//生产者消费者模型 --&gt;  利用缓冲区解决：管程法</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//生产者  ，  消费者   ，  产品  ，  缓冲区</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestPC</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        SyncContainer container=<span class="keyword">new</span> <span class="title class_">SyncContainer</span>();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Productor</span>(container).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Consumer</span>(container).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//生产者</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Productor</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line">    SyncContainer container;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Productor</span><span class="params">(SyncContainer container)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.container=container;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//生产</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line"></span><br><span class="line">            container.push(<span class="keyword">new</span> <span class="title class_">Chicken</span>(i));</span><br><span class="line">            System.out.println(<span class="string">&quot;生产了&quot;</span>+i+<span class="string">&quot;只鸡&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//消费者</span></span><br><span class="line"><span class="keyword">class</span>  <span class="title class_">Consumer</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line">    SyncContainer container;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Consumer</span><span class="params">(SyncContainer container)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.container=container;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//消费</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">100</span>; i++) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;消费了--&gt;&quot;</span>+container.pop().id+<span class="string">&quot;只鸡&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//产品</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Chicken</span>&#123;</span><br><span class="line">    <span class="type">int</span> id ;<span class="comment">//产品编号</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Chicken</span><span class="params">(<span class="type">int</span> id)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//缓冲区</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">SyncContainer</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//需要一个容器大小</span></span><br><span class="line">    Chicken[] chickens = <span class="keyword">new</span> <span class="title class_">Chicken</span>[<span class="number">10</span>];</span><br><span class="line">    <span class="comment">//容器计数器</span></span><br><span class="line">    <span class="type">int</span> count=<span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//生产者放入产品</span></span><br><span class="line">    <span class="keyword">public</span>  <span class="keyword">synchronized</span>  <span class="keyword">void</span>  <span class="title function_">push</span><span class="params">(Chicken chicken)</span>&#123;</span><br><span class="line">        <span class="comment">//如果容器满了，就需要等待消费者消费</span></span><br><span class="line">        <span class="keyword">if</span> (count==chickens.length)&#123;</span><br><span class="line">            <span class="comment">//通知消费者消费，生产等待</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="built_in">this</span>.wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//如果没有满，我们就需要丢入产品</span></span><br><span class="line">        chickens[count]=chicken;</span><br><span class="line">        count++;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//可以通知消费者消费了</span></span><br><span class="line">        <span class="built_in">this</span>.notifyAll();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//消费者消费产品</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">synchronized</span> Chicken <span class="title function_">pop</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="comment">//判断能否消费</span></span><br><span class="line">        <span class="keyword">if</span> (count==<span class="number">0</span>)&#123;</span><br><span class="line">            <span class="comment">//等待生产者生产。消费者等待</span></span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="built_in">this</span>.wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//如果可以消费</span></span><br><span class="line">         count--;</span><br><span class="line">        <span class="type">Chicken</span> <span class="variable">chicken</span> <span class="operator">=</span> chickens[count];</span><br><span class="line"></span><br><span class="line">        <span class="comment">//吃完了，通知生产者生产</span></span><br><span class="line">        <span class="built_in">this</span>.notifyAll();</span><br><span class="line">        <span class="keyword">return</span> chicken;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>







<h3 id="信号灯法"><a href="#信号灯法" class="headerlink" title="信号灯法"></a>信号灯法</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//生产消费者模式：信号灯法，标志位解决</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestPC2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">TV</span> <span class="variable">tv</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">TV</span>();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Player</span>(tv).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Watcher</span>(tv).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//生产者--&gt;演员</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Player</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line">    TV tv;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Player</span><span class="params">(TV tv)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.tv=tv;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">20</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (i%<span class="number">2</span>==<span class="number">0</span>)&#123;</span><br><span class="line">                <span class="built_in">this</span>.tv.play(<span class="string">&quot;快乐大本营播放中&quot;</span>);</span><br><span class="line">            &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="built_in">this</span>.tv.play(<span class="string">&quot;抖音：记录美好生活&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//消费者--&gt;观众</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Watcher</span> <span class="keyword">extends</span> <span class="title class_">Thread</span>&#123;</span><br><span class="line">    TV tv;</span><br><span class="line">    <span class="keyword">public</span> <span class="title function_">Watcher</span><span class="params">(TV tv)</span>&#123;</span><br><span class="line">        <span class="built_in">this</span>.tv=tv;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">20</span>; i++) &#123;</span><br><span class="line">            tv.watch();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//产品--&gt;节目</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">TV</span>&#123;</span><br><span class="line">    <span class="comment">//演员表演，观众等待</span></span><br><span class="line">    <span class="comment">//观众观看，演员等待</span></span><br><span class="line">    String voice;<span class="comment">//表演的节目</span></span><br><span class="line">    <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> <span class="literal">true</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//表演</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title function_">play</span><span class="params">(String voice)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!flag)&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="built_in">this</span>.wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">&quot;演员表演了：&quot;</span>+voice);</span><br><span class="line">        <span class="comment">//通知观众观看</span></span><br><span class="line">        <span class="built_in">this</span>.notifyAll();<span class="comment">//通知唤醒</span></span><br><span class="line">        <span class="built_in">this</span>.voice=voice;</span><br><span class="line">        <span class="built_in">this</span>.flag=!<span class="built_in">this</span>.flag;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//观看</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title function_">watch</span><span class="params">()</span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (flag)&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="built_in">this</span>.wait();</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(<span class="string">&quot;观看了：&quot;</span>+voice);</span><br><span class="line">        <span class="comment">//通知演员表演</span></span><br><span class="line">        <span class="built_in">this</span>.notifyAll();</span><br><span class="line">        <span class="built_in">this</span>.flag=!<span class="built_in">this</span>.flag;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<br>

<br>

<hr>
<br>

<br>

<h1 id="线程池"><a href="#线程池" class="headerlink" title="线程池"></a>线程池</h1><p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230630013914386.png" alt="image-20230630013914386"></p>
<p><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/image-20230630014454197.png" alt="image-20230630014454197"></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//线程池</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">TestPool</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">//1.创建服务，创建线程池</span></span><br><span class="line">        <span class="comment">//newFixedThreadPool  参数为：线程池的大小</span></span><br><span class="line">        <span class="type">ExecutorService</span> <span class="variable">service</span> <span class="operator">=</span> Executors.newFixedThreadPool(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">        service.execute(<span class="keyword">new</span> <span class="title class_">MyThread</span>());</span><br><span class="line">        service.execute(<span class="keyword">new</span> <span class="title class_">MyThread</span>());</span><br><span class="line">        service.execute(<span class="keyword">new</span> <span class="title class_">MyThread</span>());</span><br><span class="line">        service.execute(<span class="keyword">new</span> <span class="title class_">MyThread</span>());</span><br><span class="line">        service.execute(<span class="keyword">new</span> <span class="title class_">MyThread</span>());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//2.关闭连接</span></span><br><span class="line">        service.shutdownNow();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MyThread</span> <span class="keyword">implements</span> <span class="title class_">Runnable</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">run</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">辰</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/05/01/Java%E7%BA%BF%E7%A8%8B/">http://example.com/2023/05/01/Java%E7%BA%BF%E7%A8%8B/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">C·辰</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Java%E7%BA%BF%E7%A8%8B/">Java线程</a></div><div class="post_share"><div class="social-share" data-image="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/thread.webp" data-sites="wechat,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/04/11/%E8%BD%AF%E8%80%83/" title="Soft test"><img class="cover" src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Fpage2.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Soft test</div></div></a></div><div class="next-post pull-right"><a href="/2023/05/01/Java%E6%B3%A8%E8%A7%A3/" title="Java注解"><img class="cover" src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/annptation2.webp" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Java注解</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog%2Fimages%2Favatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">辰</div><div class="author-info__description">车遥马慢</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">32</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">28</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">10</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/hchenp"><i class="fab fa-github"></i><span>Gitee-HchenP</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/hchenp" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://github.com/Pxlchen?tab=projects" target="_blank" title="CSDN"><i class="fa fa-book-open"></i></a><a class="social-icon" href="https://console.cloud.tencent.com/cos/bucket?bucket=chen-1317386995&amp;region=ap-guangzhou&amp;isPublic=true" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="mailto:1107383160@qq.com" target="_blank" title="Email"><i class="fas fa-envelope-open-text"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">C2C-Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E5%AE%9E%E7%8E%B0%E3%80%90%E9%87%8D%E7%82%B9%E3%80%91"><span class="toc-number">1.</span> <span class="toc-text">线程实现【重点】</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Thread"><span class="toc-number">1.1.</span> <span class="toc-text">Thread</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F"><span class="toc-number">1.1.1.</span> <span class="toc-text">注意</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Runnable%E3%80%90-%E3%80%91"><span class="toc-number">1.2.</span> <span class="toc-text">Runnable【*】</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B0%8F%E7%BB%93"><span class="toc-number">1.3.</span> <span class="toc-text">小结</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Callable"><span class="toc-number">1.4.</span> <span class="toc-text">Callable</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lambda%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-number">1.5.</span> <span class="toc-text">Lambda表达式</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81"><span class="toc-number">2.</span> <span class="toc-text">线程状态</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%82%E5%AF%9F%E7%BA%BF%E7%A8%8B%E7%8A%B6%E6%80%81"><span class="toc-number">2.1.</span> <span class="toc-text">观察线程状态</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E5%81%9C%E6%AD%A2-%E2%80%93stop"><span class="toc-number">2.2.</span> <span class="toc-text">线程停止 –stop</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E4%BC%91%E7%9C%A0%E2%80%93sleep"><span class="toc-number">2.3.</span> <span class="toc-text">线程休眠–sleep</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E7%A4%BC%E8%AE%A9%E2%80%93yield"><span class="toc-number">2.4.</span> <span class="toc-text">线程礼让–yield</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%90%88%E5%B9%B6%E7%BA%BF%E7%A8%8B%E2%80%93join"><span class="toc-number">2.5.</span> <span class="toc-text">合并线程–join</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E4%BC%98%E5%85%88%E7%BA%A7%E2%80%93priority"><span class="toc-number">2.6.</span> <span class="toc-text">线程优先级–priority</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%88%E6%8A%A4%E7%BA%BF%E7%A8%8B%E2%80%93daemon"><span class="toc-number">2.7.</span> <span class="toc-text">守护线程–daemon</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5%E3%80%90%E9%87%8D%E7%82%B9%E3%80%91"><span class="toc-number">3.</span> <span class="toc-text">线程同步【重点】</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%B9%B6%E5%8F%91"><span class="toc-number">3.1.</span> <span class="toc-text">并发</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%89%E5%85%A8%E9%9B%86%E5%90%88CopyOnWriteArrayList"><span class="toc-number">3.1.1.</span> <span class="toc-text">安全集合CopyOnWriteArrayList</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%94%81%E6%9C%BA%E5%88%B6-%E2%80%93-synchronized"><span class="toc-number">3.2.</span> <span class="toc-text">锁机制  –  synchronized</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#synchronized%E6%96%B9%E6%B3%95"><span class="toc-number">3.2.1.</span> <span class="toc-text">synchronized方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#synchronized%E5%9D%97"><span class="toc-number">3.2.2.</span> <span class="toc-text">synchronized块</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%AD%BB%E9%94%81"><span class="toc-number">3.3.</span> <span class="toc-text">死锁</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lock%EF%BC%88%E9%94%81%EF%BC%89"><span class="toc-number">3.4.</span> <span class="toc-text">Lock（锁）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ReentrantLock"><span class="toc-number">3.5.</span> <span class="toc-text">ReentrantLock</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E9%80%9A%E4%BF%A1%E9%97%AE%E9%A2%98"><span class="toc-number">4.</span> <span class="toc-text">线程通信问题</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E8%80%85%E6%B6%88%E8%B4%B9%E8%80%85%E6%A8%A1%E5%BC%8F"><span class="toc-number">4.1.</span> <span class="toc-text">生产者消费者模式</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AE%A1%E7%A8%8B%E6%B3%95"><span class="toc-number">4.1.1.</span> <span class="toc-text">管程法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BF%A1%E5%8F%B7%E7%81%AF%E6%B3%95"><span class="toc-number">4.1.2.</span> <span class="toc-text">信号灯法</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%BA%BF%E7%A8%8B%E6%B1%A0"><span class="toc-number">5.</span> <span class="toc-text">线程池</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/07/06/Java%E5%85%AB%E8%82%A1%E6%96%87/" title="Java八股文"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javaall.gif" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java八股文"/></a><div class="content"><a class="title" href="/2023/07/06/Java%E5%85%AB%E8%82%A1%E6%96%87/" title="Java八股文">Java八股文</a><time datetime="2023-07-06T14:22:22.000Z" title="发表于 2023-07-06 22:22:22">2023-07-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/javahd.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Java后端"/></a><div class="content"><a class="title" href="/2023/07/06/%E5%90%8E%E7%AB%AF%E8%A7%84%E5%88%92/" title="Java后端">Java后端</a><time datetime="2023-07-06T14:22:22.000Z" title="发表于 2023-07-06 22:22:22">2023-07-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/06/02/MybatisPlus/" title="MybatisPlus"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/mybatisplus.svg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="MybatisPlus"/></a><div class="content"><a class="title" href="/2023/06/02/MybatisPlus/" title="MybatisPlus">MybatisPlus</a><time datetime="2023-06-02T14:22:22.000Z" title="发表于 2023-06-02 22:22:22">2023-06-02</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/05/Linux/" title="Linux"><img src= "" data-lazy-src="/img/loading.gif" data-original="https://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Linux.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Linux"/></a><div class="content"><a class="title" href="/2023/05/05/Linux/" title="Linux">Linux</a><time datetime="2023-05-05T14:22:22.000Z" title="发表于 2023-05-05 22:22:22">2023-05-05</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/05/05/Redis/" title="Redis"><img src= "" data-lazy-src="/img/loading.gif" data-original="ttps://chen-1317386995.cos.ap-guangzhou.myqcloud.com/Blog/images/Redis.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Redis"/></a><div class="content"><a class="title" href="/2023/05/05/Redis/" title="Redis">Redis</a><time datetime="2023-05-05T14:22:22.000Z" title="发表于 2023-05-05 22:22:22">2023-05-05</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By 辰</div><div class="framework-info"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn">粤ICP备2023096650号</a><span class="footer-separator">|</span><a target="_blank" rel="noopener" href="http://hchen.cloud">hchen.cloud</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><div class="js-pjax"></div><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div>
        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body></html>